import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:example/common/config/config.dart';
import 'package:example/models/models.dart';
import 'package:getx_scaffold_ohos/getx_scaffold_ohos.dart';

class HttpConfig {
  static Future<void> init({String baseUrl = UrlConst.baseUrl}) async {
    HttpService.to.setBaseUrl(baseUrl);
    final cookieJar = CookieJar();
    HttpService.to.dio.interceptors.add(CookieManager(cookieJar));

    /// 设置请求统一处理
    HttpService.to.setOnRequestHandler(
        (RequestOptions options, RequestInterceptorHandler handler) async {
      handler.next(options);
      return true;
    });

    /// 设置响应统一处理
    HttpService.to.setOnResponseHandler((resp) async {
      try{
        var result = BaseEntity.fromJson(resp.data);
        if (result.errorCode == 0){
          return null;
        }else if (result.errorCode == -1001){
          // 登录失败, 需要重新登录
          return '登录失败, 需要重新登录';
        }else{
          return result.errorMsg;
        }
      } on Exception catch(e) {
        e.printInfo();
        return '服务器异常';
      }
    });

    /// 设置错误统一处理
    HttpService.to.setOnErrorHandler((DioException err) async {
      return '服务器异常';
    });
  }
}
